import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/app_bar/app_bar_widget.dart';
import 'package:yt_devops/components/app_permission/permission_widget.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/list_empty_widget.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/text_width.dart';
import 'package:yt_devops/components/tips.dart';
import 'package:yt_devops/components/yt_extension.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/pages/mine/user_manage/models/user_manager_model.dart';
import 'package:yt_devops/pages/mine/user_manage/user_manage_controller.dart';
import 'package:yt_devops/pages/site/site_observer_list/views/my_top_tabbar.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/debounce_utils.dart';

import '../../../components/my_gesture_detector.dart';

class UserManagePage extends GetView<UserManageController> {
  const UserManagePage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return GetBuilder<UserManageController>(
      builder: (_) {
        return Scaffold(
          appBar: AppBarWidget.withRightActions(
            ResKey.userMangement.tr,
            actions: [
              PermissionWidget(
                permissionStringList: [
                  controller.nowTab['auth'],
                ],
                child: IconButton(
                  icon: const Icon(Icons.add),
                  iconSize: 26,
                  onPressed: controller.addUser,
                ),
              ),
            ],
          ),
          body: Stack(
            children: [
              Column(
                children: [
                  Container(
                    height: 54,
                    color: Colors.white,
                    child: searchWidget(context),
                  ),
                  Container(
                    color: Colors.white,
                    width: ScreenUtil().screenWidth,
                    alignment: Alignment.center,
                    padding: const EdgeInsets.only(left: 6, right: 6),
                    child: MyTopTabBar(
                      controller.tabController!,
                      controller.tabs,
                      isScrollable: false,
                      tabAlignment: TabAlignment.fill,
                    ),
                  ),
                  Gaps.vGap10,
                  Expanded(
                    child: SmartRefresher(
                        enablePullDown: true,
                        enablePullUp: true,
                        controller: controller.refreshController,
                        onRefresh: controller.onRefresh,
                        onLoading: controller.onLoading,
                        header: ListTips.classicHeader,
                        footer: ListTips.generateClassicFooter,
                        child: controller.systemList.isEmpty &&
                                controller.isLoading
                            ? ListEmptyWidget(topPosition: 82)
                            : ListView.builder(
                                controller: controller.scrollController,
                                padding: EdgeInsets.zero,
                                itemBuilder: (BuildContext context, int index) {
                                  return _buildItem(index, 0);
                                },
                                itemCount: controller.systemList.length,
                              )),
                  ),
                ],
              ),
              Visibility(
                  visible: controller.isShowPop,
                  child: MyGestureDetector(
                    behavior: HitTestBehavior.deferToChild,
                    onTap: () {
                      controller.hiddenPop();
                    },
                    child: Container(
                      height: double.infinity,
                    ),
                  ))
            ],
          ),
        );
      },
    );
  }

  _buildItem(int index, int type) {
    UserManagerModel model = controller.systemList[index];
    var statusString = (model.status != null && model.status == '0')
        ? ResKey.mineUserManagerUserValid.tr
        : ResKey.mineUserManagerUserInvalid.tr;
    double statusWidth = TextWidth.calculateTextSize(
        statusString,
        ytTextStyle(
            color: Colour.warningTextColor,
            fontSize: 12,
            fontWeight: FontWeight.normal));
    var role = '--';
    if (model.roles != null && model.roles!.isNotEmpty) {
      Roles roles = model.roles!.first;
      role = roles.roleName ?? '';
    }
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          controller.goToUserDetail(model);
        },
        child: Stack(
          children: [
            Container(
              clipBehavior: Clip.hardEdge,
              margin: const EdgeInsets.only(left: 16, right: 16),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                color: Colors.white,
              ),

              // height: 127,
              child: Column(
                children: [
                  SizedBox(
                    // height: 117,
                    child: Column(
                      children: [
                        Gaps.vGap5,
                        Row(
                          children: [
                            Container(
                              // height:20,
                              margin: const EdgeInsets.only(left: 16, top: 10),
                              child: Text(
                                model.nickName ?? '--',
                                style: ytTextStyle(
                                    fontSize: 18, fontWeight: FontWeight.w500),
                              ),
                            ),
                            const Spacer(),
                            Container(
                              height: 20,
                              width: statusWidth + 12.w,
                              margin: const EdgeInsets.only(top: 10),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: (model.status != null &&
                                          model.status == '0')
                                      ? Colour.green.withAlpha(20)
                                      : Colour.warningTextColor.withAlpha(20),
                                  borderRadius: const BorderRadius.all(
                                      Radius.circular(4))),
                              child: Text(
                                statusString,
                                style: ytTextStyle(
                                    color: (model.status != null &&
                                            model.status == '0')
                                        ? Colour.green
                                        : Colour.warningTextColor,
                                    fontSize: 12,
                                    fontWeight: FontWeight.normal),
                              ),
                            ),
                            if (controller.nowTab['resetSecret'] as bool ||
                                controller.nowTab['disable'] as bool)
                              GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTapDown: (details) {
                                  // Log.d('onTapDown=' + controller.isShowPop.toString());
                                  // if(controller.isShowPop == true){

                                  // }
                                  final tapPosition = details.globalPosition;
                                  final y =
                                      tapPosition.dy; // do something with x & y
                                  // Log.d('offset===' + y.toString());
                                  // Log.d('localPosition===' + details.localPosition.dy.toString());
                                  controller.setPopHeight(
                                      details.localPosition.dy, y);
                                  controller.selectModel =
                                      controller.systemList[index];
                                  controller.selectedIndex = index;
                                },
                                child: Container(
                                  // color: Colors.red,
                                  padding: const EdgeInsets.only(
                                      left: 4, right: 16, top: 10),
                                  child: Image.asset(
                                    ImageAssets.mineUserMangerMore,
                                    height: 20,
                                    width: 20,
                                  ),
                                ),
                              )
                            else
                              Container(
                                width: 16,
                              )
                          ],
                        ),
                        Gaps.vGap20,
                        Row(
                          children: [
                            Container(
                              width: 80,
                              height: 20,
                              // color: Colors.red,
                              margin: const EdgeInsets.only(left: 16),
                              child: Text(
                                '${ResKey.mineUserManagerOrganization.tr}：',
                                style: ytTextStyle(
                                    color: Colour.lightTextColor,
                                    fontSize: 14,
                                    fontWeight: FontWeight.normal),
                              ),
                            ),
                            SizedBox(
                              height: 20,
                              child: Text(
                                model.orgName ?? '--',
                                style: ytTextStyle(
                                    color: Colour.mainTextColor,
                                    fontSize: 14,
                                    fontWeight: FontWeight.normal),
                              ),
                            ),
                          ],
                        ),
                        Gaps.vGap10,
                        Row(
                          children: [
                            Container(
                              width: 80,
                              height: 20,
                              // color: Colors.red,
                              margin: const EdgeInsets.only(left: 16),
                              child: Text(
                                '${ResKey.mineUserManagerMobile.tr}：',
                                style: ytTextStyle(
                                    color: Colour.lightTextColor,
                                    fontSize: 14,
                                    fontWeight: FontWeight.normal),
                              ),
                            ),
                            SizedBox(
                              height: 20,
                              child: Text(
                                model.phone != null && model.phone!.isNotEmpty
                                    ? StringJudgment.hideMiddleFourDigits(
                                        model.phone.toString())
                                    : '--',
                                style: ytTextStyle(
                                    color: Colour.mainTextColor,
                                    fontSize: 14,
                                    fontWeight: FontWeight.normal),
                              ),
                            ),
                          ],
                        ),
                        Gaps.vGap10,
                        Row(
                          children: [
                            Container(
                              width: 80,
                              height: 20,
                              margin: const EdgeInsets.only(left: 16),
                              child: Text(
                                '${ResKey.mineUserManagerRole.tr}：',
                                style: ytTextStyle(
                                    color: Colour.lightTextColor,
                                    fontSize: 14,
                                    fontWeight: FontWeight.normal),
                              ),
                            ),
                            SizedBox(
                              height: 20,
                              child: Text(
                                role,
                                style: ytTextStyle(
                                    color: Colour.mainTextColor,
                                    fontSize: 14,
                                    fontWeight: FontWeight.normal),
                              ),
                            ),
                          ],
                        ),
                        Gaps.vGap10,
                        Row(
                          children: [
                            Container(
                              width: 80,
                              height: 20,
                              // color: Colors.red,
                              margin: const EdgeInsets.only(left: 16),
                              child: Text(
                                '${ResKey.mineUserManagerUserEmail.tr}：',
                                style: ytTextStyle(
                                    color: Colour.lightTextColor,
                                    fontSize: 14,
                                    fontWeight: FontWeight.normal),
                              ),
                            ),
                            SizedBox(
                              height: 20,
                              child: Text(
                                model.email != null && model.email!.isNotEmpty
                                    ? model.email.toString()
                                    : '--',
                                style: ytTextStyle(
                                    color: Colour.mainTextColor,
                                    fontSize: 14,
                                    fontWeight: FontWeight.normal),
                              ),
                            ),
                          ],
                        ),
                        Gaps.vGap10,
                      ],
                    ),
                  ),
                  Container(
                    height: 10,
                    color: Colour.backgroundColor,
                  )
                ],
              ),
            ),
            Positioned(top: 30, right: 22, child: _getPop(index))
          ],
        ));
  }

  _getPop(int index) {
    double statusWidth1 = TextWidth.calculateTextSize(
        ResKey.mineUserManagerResetPwd.tr,
        ytTextStyle(
            color: Colour.warningTextColor,
            fontSize: 16,
            fontWeight: FontWeight.normal));
    return Visibility(
      visible: controller.isShowPop && controller.selectedIndex == index,
      // visible:false,
      child: Container(
        height: controller.nowTab['resetSecret'] as bool &&
                controller.nowTab['disable'] as bool
            ? 96
            : 48,
        width: statusWidth1 + 40.w,
        // color: Colors.red,
        //设置背景图片
        decoration: const BoxDecoration(
          // color: Colors.red,
          // borderRadius: BorderRadius.all(Radius.circular(1)),
          image: DecorationImage(
            alignment: Alignment.topCenter,
            image: AssetImage(ImageAssets.mineUserMangerPopBg),
            fit: BoxFit.fill,
          ),
        ),
        // alignment: Alignment.center,
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Visibility(
                visible: controller.nowTab['resetSecret'] as bool,
                child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                      alignment: Alignment.centerLeft,
                      margin: EdgeInsets.only(
                          left: 16.w,
                          top: controller.nowTab['disable'] as bool ? 25 : 14),
                      child: Text(
                        ResKey.mineUserManagerResetPwd.tr,
                        style: ytTextStyle(fontSize: 16),
                      ),
                    ),
                    onTap: () {
                      controller.restPwd();
                    }),
              ),
              Visibility(
                visible: controller.nowTab['resetSecret'] as bool &&
                    controller.nowTab['disable'] as bool,
                child: Gaps.vGap10,
              ),
              Visibility(
                visible: controller.nowTab['disable'] as bool,
                child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                        // color: Colors.grey,
                        alignment: Alignment.centerLeft,
                        margin: controller.nowTab['resetSecret'] as bool
                            ? EdgeInsets.only(left: 16.w, bottom: 0)
                            : EdgeInsets.only(left: 16.w, top: 14),
                        child: Text(
                          controller.selectModel.status != null &&
                                  controller.selectModel.status == '0'
                              ? ResKey.mineUserManagerForbidden.tr
                              : ResKey.mineUserManagerEnable.tr,
                          style: ytTextStyle(fontSize: 16),
                        )),
                    onTap: () {
                      controller.stopUsed();
                    }),
              ),
            ]),
      ),
    );
  }

  Widget searchWidget(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: BrnSearchText(
            maxHeight: 38,
            hintStyle:
                TextStyles.styleWith(16.sp, color: Colour.diabledButtoBgColor),
            textStyle: TextStyles.f16,
            hintText: ResKey.plsEnterUserName.tr,
            innerColor: Colour.backgroundColor,
            outSideColor: Colors.transparent,
            borderRadius: BorderRadius.circular(6),
            innerPadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0),
            onTextChange: DebounceUtils.debounceInput((p0) {}),
            onTextClear: () {
              controller.searchString = '';
              controller.getUserList();
              return false;
            },
            onTextCommit: (p0) {
              controller.searchString = p0;
              controller.getUserList();
            },
          ),
        ),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () => controller.chooseOrganization(),
          child: Padding(
            padding: const EdgeInsets.only(right: 16, top: 6, bottom: 6),
            child: Image.asset(
              ImageAssets.mineUserMangerChooseOrganization,
              width: 24.w,
              height: 24.w,
              // color: Colors.white,
            ),
          ),
        ),
      ],
    );
  }
}
